package com.wxy.favorites.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import com.wxy.favorites.config.AppConfig;
import com.wxy.favorites.core.PageInfo;
import com.wxy.favorites.dto.FavoritesMoveDto;
import com.wxy.favorites.dto.SearchDto;
import com.wxy.favorites.entity.Category;
import com.wxy.favorites.entity.Favorites;
import com.wxy.favorites.security.ContextUtils;
import com.wxy.favorites.security.SecurityUser;
import com.wxy.favorites.service.*;
import com.wxy.favorites.util.HtmlUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/favorites")
@Api(tags = "收藏")
@Secured("favorites")
public class FavoritesController {

    @Autowired
    private FavoritesService favoritesService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private MomentService momentService;

    @Autowired
    private SearchTypeService searchTypeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private AppConfig appConfig;


    @Autowired
    private QuickNavigationService quickNavigationService;

    @Autowired
    private MemorandumService memorandumService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskExecutor taskExecutor;

    @PostMapping("/save")
    @ApiOperation(value = "保存书签")
    public void save(@RequestBody Favorites favorites) {
        if (favorites.getId() == null) {// 新增
            favoritesService.saveFavorites(favorites);
        } else {// 修改
            favoritesService.updateFavorites(favorites);
        }
    }

    @PostMapping("/saveLink")
    @ApiOperation(value = "保存外链")
    public void saveLink(@RequestBody Favorites favorites) {
        favoritesService.saveLink(favorites);
    }

    @GetMapping("/url")
    @ApiOperation(value = "获取标题")
    public String url(@RequestParam String url) {
        return StrUtil.isNotBlank(url) ? HtmlUtils.getTitle(url) : null;
    }

    @GetMapping("/setTop/{id}")
    @ApiOperation(value = "置顶")
    public Integer setTop(@PathVariable Integer id) {
        return favoritesService.setTop(id);
    }

    @GetMapping("/shortcut")
    @ApiOperation(value = "根据快捷口令查询书签")
    public Favorites shortcut(@RequestParam String key) {
        SecurityUser user = ContextUtils.getCurrentUser();
        return favoritesService.findByShortcut(key, user.getId());
    }

    /**
     * 用户收藏列表(分页查询)
     *
     * @param pageNum
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "用户收藏列表(分页查询)")
    public PageInfo<Category> list(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        return favoritesService.findListPage(pageNum, pageSize);
    }

    @GetMapping("/position/{categoryId}")
    @ApiOperation(value = "查询定位")
    public Category position(@PathVariable Integer categoryId) {
        return favoritesService.position(categoryId);
    }

    /**
     * 显示更多
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/more")
    @ApiOperation(value = "显示更多")
    public List<Favorites> more(@RequestParam Integer categoryId) {
        return favoritesService.findByCategoryId(categoryId);
    }

    /**
     * 查看回收站
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/recycle")
    @ApiOperation(value = "查看回收站")
    public PageInfo<Favorites> recycle(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        SecurityUser user = ContextUtils.getCurrentUser();
        return favoritesService.findRecycleByPage(user.getId(), pageNum, pageSize);
    }

    @GetMapping("/moveList")
    @ApiOperation(value = "移动列表")
    public PageInfo<Favorites> moveList(@RequestParam(required = false) String name, @RequestParam(required = false) Integer categoryId, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        return favoritesService.findPageByCategoryId(categoryId, name, pageNum, pageSize);
    }

    @PostMapping("/move")
    @ApiOperation(value = "移动书签")
    public void move(@RequestBody @Valid FavoritesMoveDto dto) {
        favoritesService.move(dto);
    }

    @GetMapping("/shareList")
    @ApiOperation(value = "查询我的分享列表")
    public PageInfo<Favorites> shareList(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        SecurityUser user = ContextUtils.getCurrentUser();
        return favoritesService.findShareByPage(user.getId(), pageNum, pageSize);
    }

    /**
     * 清空回收站
     *
     * @return
     */
    @PostMapping("/recycle/clean")
    @ApiOperation(value = "清空回收站")
    public void cleanRecycle() {
        SecurityUser user = ContextUtils.getCurrentUser();
        favoritesService.deleteAllFromRecycle(user.getId());
    }

    /**
     * 清空分享
     *
     * @return
     */
    @PostMapping("/share/clean")
    @ApiOperation(value = "清空分享")
    public void cleanShare() {
        SecurityUser user = ContextUtils.getCurrentUser();
        favoritesService.cleanShare(user.getId());
    }

    @PostMapping("/recycle/delete/{id}")
    @ApiOperation(value = "回收站删除")
    public void deleteFromRecycle(@PathVariable Integer id) {
        favoritesService.deleteById(id);
    }

    /**
     * 恢复
     *
     * @param id
     * @return
     */
    @GetMapping("/recover/{id}")
    @ApiOperation(value = "恢复")
    public void recover(@PathVariable Integer id) {
        favoritesService.recoverOne(id);
    }

    @GetMapping("/recover/all")
    @ApiOperation(value = "一键恢复")
    public void recoverAll() {
        SecurityUser user = ContextUtils.getCurrentUser();
        favoritesService.recoverAll(user.getId());
    }

    @GetMapping("/no-share/{id}")
    @ApiOperation(value = "取消分享")
    public void noShare(@PathVariable Integer id) {
        favoritesService.updateShare(id);
    }

    /**
     * 逻辑删除
     *
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @ApiOperation(value = "逻辑删除")
    public void delete(@PathVariable Integer id) {
        favoritesService.delete(id);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询")
    public Favorites query(@PathVariable Integer id) {
        return favoritesService.query(id);
    }

    @GetMapping("/search")
    @ApiOperation(value = "搜索书签")
    public SearchDto search(@RequestParam String name) {
        return favoritesService.search(name);
    }

    @GetMapping("/star")
    @ApiOperation(value = "查询常用网址")
    public List<Favorites> star() {
        SecurityUser user = ContextUtils.getCurrentUser();
        return favoritesService.findStarFavorites(user.getId());
    }

    @GetMapping("/visit/{id}")
    @ApiOperation(value = "记录访问时间")
    public void visit(@PathVariable Integer id) {
        favoritesService.visit(id);
    }

    @PostMapping("/star")
    @ApiOperation(value = "标记为常用")
    public void star(@RequestBody Favorites favorites) {
        favoritesService.star(favorites);
    }

    @PostMapping("/share")
    @ApiOperation(value = "分享书签")
    public void share(@RequestBody Favorites favorites) {
        favoritesService.share(favorites);
    }

    @PostMapping("/import")
    @ApiOperation(value = "导入")
    public void upload(@RequestParam("file") MultipartFile file) throws IOException {
        favoritesService.upload(file);
    }

    @PostMapping("/importTemplate")
    @ApiOperation(value = "模版导入")
    public void importTemplate(@RequestParam("file") MultipartFile file) throws IOException {
        favoritesService.importTemplate(file);
    }

    @PostMapping("/importHtml")
    @ApiOperation(value = "导入html")
    public void importHtml(@RequestParam("file") MultipartFile file) throws IOException {
        favoritesService.importHtml(file);
    }

    @GetMapping("/downloadTemplate")
    @ApiOperation(value = "模版下载")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        response.setContentType(ContentType.OCTET_STREAM.getValue());
        favoritesService.downloadTemplate(response.getOutputStream());
    }

    @GetMapping("/export")
    @ApiOperation(value = "导出")
    public void export(HttpServletResponse response, @RequestParam(required = false) String favorites, @RequestParam(required = false) String moment, @RequestParam(required = false) String task, @RequestParam(required = false) String navigation, @RequestParam(required = false) String memorandum, @RequestParam(required = false) String search) throws IOException, ParseException {
        response.setContentType(ContentType.OCTET_STREAM.getValue());
        favoritesService.exportFavorites(response.getOutputStream(), favorites, moment, task, navigation, memorandum, search);
    }
}
